/*
 * C/C++ Lessons Program
 * 
 * Copyright (c) 2012 Ken Zhang (cpp.china@hotmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 */


#include <stdio.h>
#include <math.h>

const double PI = 3.141592635;

/*
  Using modf()
  
  double modf(double x, double *intpart)
    extract x into 2 parts: integral part, and fractional part.
    e.g. 3.141593 = 3.000000 + 0.141593
 */
 
void test_modf()
{
	double ipart;
	double fpart = modf(PI, &ipart);
	
	printf("double modf(double x, double *intpart)\n");
	printf("  extract x into 2 parts: integral part, and fractional part.\n");
	printf("  e.g. %lf = %lf + %lf\n", PI, ipart, fpart);
}

/*
  Implement modf()

  We can use floor and ceil to implement the standard function 'modf'
  See below:
 */

double modf_new(double x, double *intpart)
{
	if (x > 0) {
		*intpart = floor(x);
	}
	else {
		*intpart = ceil(x);
	}
	
	return x - *intpart;
}

void test_mod_imp()
{
	double ipart;
	double fpart = modf_new(-PI, &ipart);
	
	printf("double modf_new(double x, double *intpart)\n");
	printf("  extract x into 2 parts: integral part, and fractional part.\n");
	printf("  e.g. %lf = %lf + %lf\n", PI, ipart, fpart);	
}

/*
  double frexp(double x, int *exp);
  ret * 2^exp = x

  Output: 0.625000 * 2^4 = 10.000000
 */

void test_frexp ()
{
	double param, result;
	int n;

	param = 10.0;
	result = frexp (param , &n);
	printf ("%lf * 2^%d = %f\n", result, n, param);
}

int main()
{
	test_modf();
	test_mod_imp();
	test_frexp();
	return 0;
}
